CSS 消息气泡实现

前端页面开发中经常需要实现消息气泡样式,比如:

messagebubble3.png

实际上上述两种效果实现起来,并不复杂,接下来我们就来实战一下。

1. 构建消息框

消息框主体很简单,一个div,设置一下背景颜色、border-radius等即可:

.message1,.message2 {
  width: 200px;
  height: 80px;
  margin: 100px auto;
  background-color: green;
  border-bottom-color:green;/*为了给after伪元素自动继承*/
  color: #fff;
  font-size: 12px;
  font-family: Arial;
  line-height: 18px;
  padding: 5px 12px 5px 12px;
  box-sizing: border-box;
  border-radius: 6px;
  position: relative;
  word-break: break-all;
}

<body>
  <div class="message1">
    Demos 代码演示、代码片段 - 读你,欢迎来到读你,http://dunizb.com/demo/
  </div>

  <div class="message2">
    Demos 代码演示、代码片段 - 读你,欢迎来到读你,http://dunizb.com/demo/
  </div>
</body>

messagebubble2.png

2 三角形箭头

接下来我们实现一下图一中第一个消息气泡样式,这个样式相对简单:只需在消息框主体之前插入一个元素,然后再旋转45度即可,在现有元素之前插入其他元素首选before

.message1::before {
  content: '';
  width: 20px; 
  height: 20px;
  background-color: inherit;
  left: -10px; /*向左侧外部延伸箭头box的一半宽度*/
  position: absolute;
  transform: rotate(45deg); /*旋转45度*/
  top:50%; /*箭头在数值方向上居中*/
  margin-top: -5px;
}

messagebubble4.png

3 圆弧型箭头

圆弧型箭头,稍微复杂些。由于涉及到弧度部分,可以考虑利用border来实现。首先我们通过after实现一个吸附在消息框右部的矩形框:

.message2::after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  right: -24px;
  top: 0px;
  background-color: red; /*为显示需要*/
} 

messagebubble5.png

前面已经说到,我们真正需要的是通过border来实现弧形效果,所以这里必然需要设置border,不过并不是所有方向都需要设置border,只需要设置底部和左部:

.message2::after {
    content: '';
    position: absolute;
    width: 20px;
    height: 20px;
    right: -24px;
    top: 0px;
    background-color: red;
    border-width: 0 0 20px 20px;
    border-style: solid;
    border-left-color: blue;
    border-bottom-color: yellow;
} 

messagebubble6.png

接下来再加上右下角弧度:

.message2::after {
  ...
  border-bottom-right-radius: 60px;
} 

messagebubble7.png

此时可以看到,基本的雏形已经出来了,接下来就是重新设置颜色了。

.message2::after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  right: -24px;
  top: 0px;
  border-width: 0 0 20px 20px;
  border-style: solid;
  border-left-color: transparent;
  border-bottom-color:inherit;
  border-bottom-right-radius: 60px;
} 

messagebubble9.png

大功告成!

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值